import {
  AfterContentInit,
  ChangeDetectorRef,
  Component,
  Inject,
  ViewChild,
  ViewEncapsulation,
  Renderer,
  ElementRef, OnInit, OnDestroy
} from '@angular/core';
import {EventsService} from '@core/events/events.service';
import {DOCUMENT} from '@angular/platform-browser';
import {SeedInfiniteScroll} from '@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component';
import {Subject} from 'rxjs';
import {ToolsService} from "@shared/service/tools/tools.service";
import {TrainService} from "@train/train.service";

import {ActivatedRoute, Params, Router} from "@angular/router";
import {
  CalendarBtnConfig, SNSResult, StudentCallNameCountResult,
  StudentCallNameResultVO
} from "@interface/index";
import {AuthService} from "@shared/service/auth/auth.service";

@Component({
  selector: 'app-count',
  templateUrl: './count.component.html',
  styleUrls: ['./count.component.scss'],
  host: {id: 'goods-train'},
  encapsulation: ViewEncapsulation.None
})
export class CountComponent implements OnInit, AfterContentInit, OnDestroy {
  public signAll: number;  // 总数
  public signNum: number;  // 已签到数
  public percent: number;
  public firstLoad = true;
  public allAngle = 0;
  public page = 1;
  public startTime: Date;
  public endTime: Date;
  public arr: Array<StudentCallNameResultVO> = [];
  @ViewChild('modal') modal;
  @ViewChild('header') header;
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  private ngUnsubscribe: Subject<void> = new Subject<void>();
  public btnConfig: CalendarBtnConfig = new CalendarBtnConfig();
  public orgUserId: '';
  constructor(
    public events: EventsService,
    private cdRef: ChangeDetectorRef,
    private renderer: Renderer,
    private ele: ElementRef,
    private trainSer: TrainService,
    private tools: ToolsService,
    public router: Router,
    private route: ActivatedRoute,
    @Inject(DOCUMENT) private document,
    private authSer: AuthService
  ) {
    this.route.queryParams.subscribe((params: Params) => {
      this.orgUserId = params['authOrgId'];
      this.authSer.setAuthOrgId(params['authOrgId']);
    });
    this.setCalenderBtn();
  }
  setCalenderBtn() {
    const btnConfig = this.btnConfig;
    btnConfig.lastDay = btnConfig.today = btnConfig.lastWeek = btnConfig.lastWeek = btnConfig.week
      = btnConfig.month = btnConfig.lastMonth = true;
  }

  /**
   * @desc 获取数据
   * @author ouxh
   * @param Refresh 是否刷新列表
   */
  getInfo(Refresh: boolean) {
    let tempTime;
    this.endTime ? tempTime = this.endTime : tempTime = this.startTime;
    this.trainSer.getCourseCount(this.startTime, tempTime, this.page, this.orgUserId).subscribe((res) => {
      if (Refresh) {
        this.arr = [];
        this.page = 1;
      }
      this.page++;
      if (res.result === '0') {
        if (this.infiniteScroll) {
          this.infiniteScroll.complete();
        }
        this.arr = [...this.arr, ...res.data.list];
        this.firstLoad = false;
        if (res.data['hasNextPage']) {
          this.infiniteScroll.enable(true);
        } else {
          this.infiniteScroll.enable(false);
        }
        this.cdRef.detectChanges();
      }
    });
    if (Refresh) {
      this.getCount(this.startTime, tempTime);
    }
  }

  getCount(startDate, endDate) {
    this.trainSer.getfindSignCount(startDate, endDate, this.orgUserId).subscribe((res: SNSResult<StudentCallNameCountResult>) => {
      if (res.result === '0') {
        this.percent = res.data.percentum;
        this.allAngle = (res.data.percentum / 100 * 360);
        this.signNum = res.data.signNum;
        this.signAll = res.data.signAll;
        this.cdRef.detectChanges();
      }
    });
  }

  goEach(classId, teacherId, properties) {
    const startDateJson = this.getTimeJson(this.startTime);
    let endDateJson;
    if (this.endTime) {
      endDateJson = this.getTimeJson(this.endTime);
    } else {
      endDateJson = startDateJson;
    }
    this.router.navigate([`/train/course`], {
      queryParams: {
        teacherId: teacherId,
        classId: classId,
        properties: properties,
        beginTime: this.tools.getTimeStr(startDateJson, '', '-'),
        endTime: this.tools.getTimeStr(endDateJson, '', '-')
      }
    });
  }


  modalConfirm(val) {
    this.startTime = val[0];
    this.endTime = val[1];
    this.getInfo(true);

  }

  getTimeJson(date: Date) {
    const startTimeYear = date.getFullYear();
    const startTimeMon = date.getMonth();
    const startTimeDay = date.getDate();
    const startDate = {
      y: startTimeYear,
      m: startTimeMon,
      d: startTimeDay
    };
    return startDate;
  }

  ngOnInit() {
  }

  ngAfterContentInit() {
    this.startTime = new Date();
    // this.getInfo(true);
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

}
